/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    useTheme,
    InputLine,
    TextArea,
    Select,
    Text,
    BlobInputList,
    useToast,
    Button
} from "customize-easy-ui-component";
import {
    InspectRecordLayout, InternalItemProps, SelectHookfork, useInputControlSure, useItemInputControl
} from "../../common/base";
import {EditStorageContext} from "../../StorageContext";
import {Each_ZdSetting, useTableEditor} from "../../hook/useRepTableEditor";
import {useMeasureInpFilter} from "../../common/hooks";
import {useUppyUpload} from "../../hook/useUppyUpload";
import {useMedia} from "use-media";
import {assertNamesUnique} from "../../common/eHelper";


const itemA测点位置=['示图说明','_FILE_部位','检测结果']
export const ResultDiagram=
  React.forwardRef((
    { children, show ,alone=true,redId,nestMd, repId}:InternalItemProps,  ref
  ) => {
      const theme = useTheme();
      const {modified,setModified,} =React.useContext(EditStorageContext) as any;
      const [getInpFilter] = useMeasureInpFilter(null, itemA测点位置,);
      const {inp, setInp,onSure} = useInputControlSure({ ref,redId,nestMd });
      const onFinish = React.useCallback(async(upfile: any, del:boolean) => {
          onSure({...inp, '_FILE_部位': upfile});
          !modified && setModified(true);
      }, [inp, modified,onSure,setModified]);
      // const [uploadDom]=useUppyUpload({ repId:repId!, inp, setInp, onSure,
      //     field:'_FILE_部位', maxFile:1, onFinish,
      // });
      const [uploadDom]=useUppyUpload({ repId:repId!,
          maxFile:1, onFinish, storeObj: inp?._FILE_部位
      });

    return (
      <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show} redId={redId} nestMd={nestMd}
                           alone={alone}  label={'超声波检测结果，示意图'}>
          <InputLine label='检测示意图（文字说明）：'>
              <BlobInputList value={inp?.示图说明 || ''}   datalist={["参考上面的位置示图","参考上面设备编号 的位置示图"]}
                             onListChange={v => setInp({...inp, 示图说明: v || undefined}) } />
          </InputLine>
          检测示意图：
          {uploadDom}
        检测结果:
        <TextArea  value={inp?.检测结果 ||''} rows={4}
                 onChange={e => setInp({ ...inp, 检测结果: e.currentTarget.value||undefined}) } />
      </InspectRecordLayout>
    );
} );

const 检测方法选=['一次反射波法' ];
const 扫查方式选=['垂直焊缝平行扫查' ];
/**必须从上级的 _$设备名称 _$eqpcod，才能提取：分项报告只能约束到特定标号的分项对象底下提取的，所以没有像主报告一样能读到 # orc=parentOrc['_SONIC_TS_'+surpId];。
 * */
export const config测量仪 = [
    [['设备名称', '_$设备名称'], ['部件名称', '部件名称'] ],
    [['设备编号', '_$eqpcod'], ['部件编号', '部件编号'] ],
    [['设备类别','设备类'],['规格尺寸','规格尺寸']],
    [['材质', '材质'], ['表面状态', '表面']],
    [['热处理状态', '热处理'], ['检测时机', '检测时机']],
    [['检测部位', '检测部位'], ['坡口型式', '坡口']],
    [['检测比例',{n:'检测比',u:'%'}], ['检测标准', '标准']],
    [['合格级别', '合格级'], ['检测技术等级', '技术级']],
    [['仪器型号', '仪器型'], ['仪器编号', '仪器号']],
    [['探头型号', '探头型'], ['试块型号', '试块型']],
    [['耦 合 剂', '耦合剂'], ['耦合补偿', {n:'耦补偿',u:'dB'}]],
    [['检测方法', {n:'检测法',t:'l',l:检测方法选}], ['检测灵敏度', {n:'灵敏度',u:'dB'}]],
    [['检测面', '检测面'], ['扫查方式', {n:'扫查式',t:'l',l:扫查方式选}]],
];


export const config附设装置=[['附表序号','n',35],['设备种类','y',150,(obj,setObj)=>{
    return <Select inputSize="md" css={{minWidth:'140px',fontSize:'1.3rem',padding:'0 1rem'}}
                   value={obj?.y ||''} onChange={e => setObj({ ...obj, y: e.currentTarget.value||undefined}) }>
        <option></option> <option>桥架型起重机、臂架型起重机、电动葫芦等起重设备</option> <option>升降机等登机设备</option> </Select>
}],['设备名称','t',80],['设备型号','m',70],['额定起重量','Q',50],
    ['产品编号','p',68],['制造单位','u',112],['检验结果','r',35,(obj,setObj)=>{
        return <SelectHookfork value={ obj?.r ||''} onChange={e => setObj({ ...obj, r: e.currentTarget.value||undefined}) }/>
    }],['备注','Z',80]] as Each_ZdSetting[];
const 默认附设装置=[{n:'1',y:'桥架型起重机、臂架型起重机、电动葫芦等起重设备'},{n:'2',y:'桥架型起重机、臂架型起重机、电动葫芦等起重设备'},{n:'3',y:'升降机等登机设备'}];
// 焊缝编号
export const config部位汇总=[['焊缝编号','n',110],['壁厚mm','h',70],['缺陷编号','f',95],['缺陷位置','p',95],
               ['长度mm','L',80],['深度mm','D',75],['高度mm','H',75],['波幅dB','b',70],['缺陷类型','t',95],['评定级别','c',70],['备注/检测长度','m',180]] as Each_ZdSetting[];
// const 默认漏磁检=[{n:'直管'}];
const itemA部位汇总=['评定表'];
export const EvaluationForm=
    React.forwardRef(({ children, show ,alone=true,refWidth,redId,nestMd}:InternalItemProps,  ref
    ) => {
        const [getInpFilter]=useMeasureInpFilter(null,itemA部位汇总,);
        const {inp, setInp} = useItemInputControl({ ref,redId,nestMd });
        const headview=<Text variant="h5">
            壁厚测定：各部位实测点数和最小壁厚的汇总。
        </Text>;
        const [render部位汇总]=useTableEditor({inp, setInp,  headview,
            config: config部位汇总, table:'评定表', column:4,  maxRf:3});

        return (
            <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show}  redId={redId} nestMd={nestMd}
                                 alone={alone}  label={'焊接接头超声检测-结果评定表'}>
                {render部位汇总}
            </InspectRecordLayout>
        );
    } );


/**【开发测试用的】
 * */
export const EntranceSetup =
    React.forwardRef((
        {children, show, alone = true, repId, verId, rep}: InternalItemProps, ref
    ) => {
        const atPrint = useMedia('print');
        const toast = useToast();
        const checkName = true;      //开发测试完，改成=false, 测试时 REACT_APP_TEST 需设置， 开发模式的校对开关。
        const doCheckNames = React.useCallback((verId: string) => {
            //【承压更少项目】，那些属于公共模板目录的 分项报告的唯一性检查在对方自己检查看。
            const result = assertNamesUnique([{value: rep?.tzFields},
                {value: config测量仪, type:'esnt'},
                {value:[...itemA部位汇总,...itemA测点位置, ]},
            ]);
            toast({title: "完成！", subtitle: result ? "没发现冲突" : "测试开关没开", intent: "success"});
        }, [rep,toast]);
        const getInpFilter = React.useCallback((par: any) => {}, []);
        const {inp, setInp} = useItemInputControl({ref});
        if (atPrint) return null;
        else return (
            <InspectRecordLayout inp={inp} setInp={setInp} getInpFilter={getInpFilter} show={show}
                                 alone={alone} label={'初始化本报告，默认值配置等'}>
                {checkName && <div>
                    <Text variant="h5">
                        构建开发模板时的工具：校验模板的存储name冲突；
                    </Text>
                    <Button intent='primary' onPress={() => {
                        doCheckNames(verId!);
                    }}>校验模板name唯一性</Button>
                </div>
                }
                <hr/>
            </InspectRecordLayout>
        );
    });
